//
//  FetchMarketProducts.swift
//  Nahuo
//
//  Created by zang qilong on 2017/5/15.
//  Copyright © 2017年 zang qilong. All rights reserved.
//

import UIKit
import YTKNetwork
import SwiftyJSON

enum ProductOrderType:Int {
    case reverseTime = 0
    case smart
    case reverseFavourite
    case priceToptoBottom
    case priceBottomToTop
}

class FetchMarketProducts: YTKRequest {
    
    var type:String
    let page:Int
    let limit = 20
    var priceOpt:Int = 0
    var orderType:ProductOrderType = .reverseTime
    var productArray:[Product] = [Product]()
    
    init(type:String, page:Int, _ priceRange:Int = 0, _ orderType:ProductOrderType = .reverseTime) {
        self.type = type
        self.page = page
        self.priceOpt = priceRange
        self.orderType = orderType
    }
    
    override func requestUrl() -> String {
        return "/market/get-products"
    }
    
    override func requestMethod() -> YTKRequestMethod {
        return .GET
    }
    
    override func requestArgument() -> Any? {
        return ["type": "\(type)"]
    }
    
    override func requestHeaderFieldValueDictionary() -> [String : String]? {
        let parameterDict = ["page": "\(page)", "limit": "\(limit)", "priceOpt": "\(priceOpt)", "orderOpt": "\(orderType.rawValue)"]
        var authHeader = NaHuoHttpUtil.sharedInstance.generateVerifyMobileHeader()
        for (key, value) in parameterDict {
            authHeader[key] = value
        }
        return authHeader
    }
    
    func startFetchProducts(complection:@escaping (() -> Void)) {
        self.startWithCompletionBlock(success: { (request) in
            let json = JSON(request.responseObject as Any)
            guard let code = json["code"].int else {
                printCodeError(request: request as! YTKRequest)
                return
            }
            
            guard code == 0 else {
                return
            }
            if let data = json["data"].arrayObject {
                if self.page == 0 {
                    self.productArray.removeAll()
                }
                for obj in data {
                    if let product = Product.yy_model(withJSON: obj) {
                        self.productArray.append(product)
                        print(product.description);
                    }
                }
                complection()
            }
        }) { (request) in
            
        }
    }

}
